package com.ydd.common.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author Tom
 */
public class DateUtils {
	private StringBuffer buffer = new StringBuffer();
	private static String ZERO = "0";
	private static DateUtils date;
	public static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
	public static SimpleDateFormat format1 = new SimpleDateFormat(
			"yyyyMMdd HH:mm:ss");

	public String getNowString() {
		Calendar calendar = getCalendar();
		buffer.delete(0, buffer.capacity());
		buffer.append(getYear(calendar));

		if (getMonth(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getMonth(calendar));

		if (getDate(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getDate(calendar));
		if (getHour(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getHour(calendar));
		if (getMinute(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getMinute(calendar));
		if (getSecond(calendar) < 10) {
			buffer.append(ZERO);
		}
		buffer.append(getSecond(calendar));
		return buffer.toString();
	}

	private static int getDateField(Date date,int field) {
		Calendar c = getCalendar();
		c.setTime(date);
		return c.get(field);
	}
	public static int getYearsBetweenDate(Date begin,Date end){
        int yearNow = getDateField(end,Calendar.YEAR);
        int monthNow = getDateField(end,Calendar.MONTH) + 1;//注意此处，如果不加1的话计算结果是错误的
        int dayOfMonthNow = getDateField(end,Calendar.DAY_OF_MONTH);
        int yearBirth = getDateField(begin,Calendar.YEAR);
        int monthBirth = getDateField(begin,Calendar.MONTH);
        int dayOfMonthBirth = getDateField(begin,Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                //monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                } else {
                    //do nothing
                }
            } else {
                //monthNow>monthBirth
                age--;
            }
        } else {
            //monthNow<monthBirth
            //donothing
        }
        return age;
	}
	
	/**
	 * 对传入的时间字串进行格式化
	 * 
	 * @param time
	 *            要格式化的时间，如果为空则取当前时间
	 * @param format
	 *            返回值的形式，为空则按"yyyy-MM-dd HH:mm:ss"格式化时间
	 * @return 格式化后的时间字串
	 */
	public static String formatDateStrToStr(String time, String format) {
		return formatDate(formatDateStr(time, format), format);
	}
	
	/**
	 * 对传入的时间字串进行格式化，并返回一个Date对象
	 * 
	 * @param time
	 *            要格式化的时间，如果为空则取当前时间
	 * @param format
	 *            返回值的形式，为空则按"yyyy-MM-dd HH:mm:ss"格式化时间
	 * @return 格式化后的时间
	 */
	public static Date formatDateStr(String time, String format) {

		if (time == null || time.equals("")) {
			// 获取当前time
			time = formatDate(null, null);
		}
		if (format == null || format.equals("")) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		ParsePosition pos = new ParsePosition(0);// 从0开始解析
		Date strtodate = formatter.parse(time, pos);
		return strtodate;
	}
	
	/**
	 * 对传入的时间进行格式化
	 * 
	 * @param time
	 *            要格式化的时间，如果为null则取当前时间
	 * @param format
	 *            返回值的形式，为空则按"yyyy-MM-dd HH:mm:ss"格式化时间
	 * @return 格式化后的时间字串
	 */
	public static String formatDate(Date time, String format) {
		if (time == null) {
			time = new Date();
		}// 获取当前time
		if (format == null || format.equals("")) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		String dateString = formatter.format(time);
		return dateString;
	}
	
	public static int getMonthsBetweenDate(Date begin,Date end){
		int bMonth=getDateField(begin,Calendar.MONTH);
		int eMonth=getDateField(end,Calendar.MONTH);
		return eMonth-bMonth;
	}
	public static int getWeeksBetweenDate(Date begin,Date end){
		int bWeek=getDateField(begin,Calendar.WEEK_OF_YEAR);
		int eWeek=getDateField(end,Calendar.WEEK_OF_YEAR);
		return eWeek-bWeek;
	}
	public static int getDaysBetweenDate(Date begin,Date end){
		int bDay=getDateField(begin,Calendar.DAY_OF_YEAR);
		int eDay=getDateField(end,Calendar.DAY_OF_YEAR);
		return eDay-bDay;
	}	
	 /**
     * 日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
	 * @throws ParseException 
     */
    public static String getWeekOfDateString(Date dt) throws ParseException {

        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
        }
        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd");
		String a = dateFm.format(dt);
        return a +"  "+ weekDays[w];
    }
    
	 /**
     * 日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
	 * @throws ParseException 
     */
    public static String getDateString(Date dt) throws ParseException {

        SimpleDateFormat dateFm = new SimpleDateFormat("yyyyMMdd");
		String a = dateFm.format(dt);
        return a;
    }
    
    public static int getWeekOfDateInt(Date dt) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
        }
        if( w == 0){
        	w = 7;
        }
        return w;
    }
    
	 /**
     * 获取当前日期+-<br>
     * 
     * @param dt
     * @return date
	 * @throws ParseException 
     */
    public static Date getDateAddDel(Date dt,int i) throws ParseException {
    	SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		Calendar date = Calendar.getInstance();
		date.setTime(dt);
		date.set(Calendar.DATE, date.get(Calendar.DATE) + i);
		Date endDate = dft.parse(dft.format(date.getTime()));
		return endDate;
    } 
    
    
	public static void main(String args[]) throws ParseException{
		SimpleDateFormat dateFm = new SimpleDateFormat("yyyyMMdd");
		Date dt = new Date();
		Date ed = getDateAddDel(dt,1);
		String db = "20140729";
		Date bb = dateFm.parse(db);
		if(bb.after(ed)){
			System.out.print("false");
		}else{
			System.out.print("true");
		}
		
	}

	/**
	 * 获取date年后的amount年的第一天的开始时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficYearStart(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.YEAR, amount);
		cal.set(Calendar.DAY_OF_YEAR, 1);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取date年后的amount年的最后一天的终止时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficYearEnd(Date date,int amount) {
		Date temp = getStartDate(getSpecficYearStart(date,amount + 1));
		Calendar cal = Calendar.getInstance();
		cal.setTime(temp);
		cal.add(Calendar.DAY_OF_YEAR, -1);
		return getFinallyDate(cal.getTime());
	}

	/**
	 * 获取date月后的amount月的第一天的开始时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficMonthStart(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, amount);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取当前自然月后的amount月的最后一天的终止时间
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficMonthEnd(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getSpecficMonthStart(date,amount + 1));
		cal.add(Calendar.DAY_OF_YEAR, -1);
		return getFinallyDate(cal.getTime());
	}

	/**
	 * 获取date周后的第amount周的开始时间（这里星期一为一周的开始）
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficWeekStart(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.setFirstDayOfWeek(Calendar.MONDAY); /* 设置一周的第一天为星期一 */
		cal.add(Calendar.WEEK_OF_MONTH, amount);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return getStartDate(cal.getTime());
	}

	/**
	 * 获取date周后的第amount周的最后时间（这里星期日为一周的最后一天）
	 * 
	 * @param amount
	 *            可正、可负
	 * @return
	 */
	public static Date getSpecficWeekEnd(Date date,int amount) {
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY); /* 设置一周的第一天为星期一 */
		cal.add(Calendar.WEEK_OF_MONTH, amount);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		return getFinallyDate(cal.getTime());
	}
	
	public static Date getSpecficDateStart(Date date,int amount){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_YEAR, amount);
		return getStartDate(cal.getTime());
	}

	/**
	 * 得到指定日期的一天的的最后时刻23:59:59
	 * 
	 * @param date
	 * @return
	 */
	public static Date getFinallyDate(Date date) {
		String temp = format.format(date);
		temp += " 23:59:59";

		try {
			return format1.parse(temp);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 得到指定日期的一天的开始时刻00:00:00
	 * 
	 * @param date
	 * @return
	 */
	public static Date getStartDate(Date date) {
		String temp = format.format(date);
		temp += " 00:00:00";

		try {
			return format1.parse(temp);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 
	 * @param date 指定比较日期
	 * @param compareDate 
	 * @return
	 */
	public static boolean isInDate(Date date,Date compareDate){
		if(compareDate.after(getStartDate(date))&&compareDate.before(getFinallyDate(date))){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 得到当前系统时间Timestamp
	 * @return
	 */
	public static Timestamp getNowTimestamp(){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		Timestamp now = Timestamp.valueOf(df.format(new Date()));
		return now;
	}
	
	/**
	  * 格式化时间
	  * Locale是设置语言敏感操作
	  * @param formatTime
	  * @return
	  */
	 public static String getTimeStampNumberFormat(Timestamp formatTime) {
	        SimpleDateFormat m_format = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss", new Locale("zh", "cn"));
	        return m_format.format(formatTime);
	  }
	 
	 /**
	     * XX分钟XX小时前<br>
	     * 
	     * @param dt
	     * @return 当前日期是星期几
		 * @throws ParseException 
	     */
	 public static String getTimeFromNow2(String dt) throws ParseException {
	    	Timestamp now = getNowTimestamp();
	    	Timestamp ts = new Timestamp(System.currentTimeMillis());  
	        try {  
	            ts = Timestamp.valueOf(dt);  
	            System.out.println(ts);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	  		int del = timeSubtractionSecond(now,ts);
	  		if(del<60){
	  			return String.valueOf(del)+"秒前";
	  		}else if(del/60<60){
	  			return String.valueOf((int)(del/60))+"分钟前";
	  		}else if(del/3600<24){
	  			return String.valueOf((int)(del/3600))+"小时前";
	  		}
	  		else{
//	  		if(del/86400<30){
//	  			return String.valueOf((int)(del/3600))+"小时前";
	  			Timestamp tts = new Timestamp(System.currentTimeMillis()); 
	  			tts = Timestamp.valueOf(dt);
	  	        DateFormat dateFm = new SimpleDateFormat("yyyy年MM月dd日");
	  			return dateFm.format(tts);
	  		}
	 }
	 
	/**
	  * 计算时间差
	  * @param from
	  * @param to
	  * @param str H:小时 M:分钟 S:秒
	  * @return
	 * @throws ParseException 
	  */
	 public static int timeSubtraction (Timestamp from,Timestamp to,String str) throws ParseException {
	        SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");
	        long t1 = 0L;
	        long t2 = 0L;
	        t1 = timeformat.parse(getTimeStampNumberFormat(from)).getTime();
	        t2 = timeformat.parse(getTimeStampNumberFormat(to)).getTime();
	        int hours=(int) ((t1 - t2)/3600000);
	        int minutes=(int) (((t1 - t2)/1000-hours*3600)/60);
	        int second=(int) ((t1 - t2)/1000-hours*3600-minutes*60);
	        int result = 0;
	        if("H".equals(str)){
	        	result = hours;
	        } else  if("M".equals(str)){
	        	result = minutes;
	        } else  if("S".equals(str)){
	        	result = second;
	        } 
	        return result;
	 }
	 public static int timeSubtractionSecond (Timestamp from,Timestamp to) throws ParseException {
	        SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");
	        long t1 = 0L;
	        long t2 = 0L;
	        t1 = timeformat.parse(getTimeStampNumberFormat(from)).getTime();
	        t2 = timeformat.parse(getTimeStampNumberFormat(to)).getTime();
	        int hours=(int) ((t1 - t2)/3600000);
	        int minutes=(int) (((t1 - t2)/1000-hours*3600)/60);
	        int second=(int) ((t1 - t2)/1000-hours*3600-minutes*60);
	        int result = 0;
	        return hours*3600+minutes*60+second;
	 }
	 
	    public static String getTimeFromNow(String dt) throws ParseException { 
	    	Timestamp ts = new Timestamp(System.currentTimeMillis());  
	        try {  
	            ts = Timestamp.valueOf(dt);  
	            System.out.println(ts);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    	String str=null;
//	        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:m:s");  
//	        Date date = format.parse("2013-11-11 18:35:35");  
	        str=format(ts);
			return str;  
	    } 
	 	private static final long ONE_MINUTE = 60000L;  
	    private static final long ONE_HOUR = 3600000L;  
	    private static final long ONE_DAY = 86400000L;  
	    private static final long ONE_WEEK = 604800000L;  
	    
	    private static final String ONE_SECOND_AGO = "秒前";  
	    private static final String ONE_MINUTE_AGO = "分钟前";  
	    private static final String ONE_HOUR_AGO = "小时前";  
	    private static final String ONE_DAY_AGO = "天前";  
	    private static final String ONE_MONTH_AGO = "月前";  
	    private static final String ONE_YEAR_AGO = "年前";  
	    private static long toSeconds(long date) {  
	        return date / 1000L;  
	    }  
	    private static long toMinutes(long date) {  
	        return toSeconds(date) / 60L;  
	    }  
	    private static long toHours(long date) {  
	        return toMinutes(date) / 60L;  
	    }  
	    private static long toDays(long date) {  
	        return toHours(date) / 24L;  
	    }  
	    private static long toMonths(long date) {  
	        return toDays(date) / 30L;  
	    }  
	    private static long toYears(long date) {  
	        return toMonths(date) / 365L;  
	    }  
	    
	    public static String format(Date date) {  
	        long delta = new Date().getTime() - date.getTime();  
	        if (delta < 1L * ONE_MINUTE) {  
	            long seconds = toSeconds(delta);  
	            return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;  
	        }  
	        if (delta < 45L * ONE_MINUTE) {  
	            long minutes = toMinutes(delta);  
	            return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;  
	        }  
	        if (delta < 24L * ONE_HOUR) {  
	            long hours = toHours(delta);  
	            return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;  
	        }  
	        if (delta < 48L * ONE_HOUR) {  
	            return "昨天";  
	        }  
	        if (delta < 30L * ONE_DAY) {  
	            long days = toDays(delta);  
	            return (days <= 0 ? 1 : days) + ONE_DAY_AGO;  
	        }  
	        if (delta < 12L * 4L * ONE_WEEK) {  
	            long months = toMonths(delta);  
	            return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;  
	        } else {  
	            long years = toYears(delta);  
	            return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;  
	        }  
	    }  
	    
	 
	private int getYear(Calendar calendar) {
		return calendar.get(Calendar.YEAR);
	}

	private int getMonth(Calendar calendar) {
		return calendar.get(Calendar.MONDAY) + 1;
	}

	private int getDate(Calendar calendar) {
		return calendar.get(Calendar.DATE);
	}

	private int getHour(Calendar calendar) {
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	private int getMinute(Calendar calendar) {
		return calendar.get(Calendar.MINUTE);
	}

	private int getSecond(Calendar calendar) {
		return calendar.get(Calendar.SECOND);
	}

	private static Calendar getCalendar() {
		return Calendar.getInstance();
	}

	public static DateUtils getDateInstance() {
		if (date == null) {
			date = new DateUtils();
		}
		return date;
	}
}
